import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Layout from '../components/Layout.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: { requiresAuth: false }
  },
  {
    path: '/test',
    name: 'Test',
    component: () => import('../views/Test.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/icon-test',
    name: 'IconTest',
    component: () => import('../views/IconTest.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/monaco-test',
    name: 'MonacoTest',
    component: () => import('../views/MonacoTest.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: Layout,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue')
      },
      // 个人信息路由
      {
        path: 'profile',
        name: 'UserProfile',
        component: () => import('../views/profile/UserProfile.vue')
      },
      // 用户管理路由
      {
        path: 'user-management/users',
        name: 'Users',
        component: () => import('../views/user-management/Users.vue')
      },
      {
        path: 'user-management/user-groups',
        name: 'UserGroups',
        component: () => import('../views/user-management/UserGroups.vue')
      },
      {
        path: 'user-management/roles',
        name: 'Roles',
        component: () => import('../views/user-management/RolesSimple.vue')
      },
      {
        path: 'user-management/menu-permissions',
        name: 'MenuPermissions',
        component: () => import('../views/user-management/MenuPermissionManager.vue')
      },
      // CMDB路由
      {
        path: 'cmdb/hosts',
        name: 'Hosts',
        component: () => import('../views/cmdb/Hosts.vue')
      },
      {
        path: 'cmdb/remote-connections',
        name: 'RemoteConnections',
        component: () => import('../views/cmdb/RemoteConnectionManager.vue')
      },
      {
        path: 'cmdb/host-groups',
        name: 'HostGroups',
        component: () => import('../views/cmdb/HostGroups.vue')
      },
      {
        path: 'cmdb/environments',
        name: 'Environments',
        component: () => import('../views/cmdb/Environments.vue')
      },
      {
        path: 'cmdb/host-types',
        name: 'HostTypes',
        component: () => import('../views/cmdb/HostTypes.vue')
      },
      {
        path: 'cmdb/database-instances',
        name: 'DatabaseInstances',
        component: () => import('../views/cmdb/DatabaseInstances.vue')
      },
      {
        path: 'cmdb/sql-audit',
        name: 'SQLAudit',
        component: () => import('../views/cmdb/SQLAudit.vue')
      },
      {
        path: 'cmdb/ssh-terminal/:hostId',
        name: 'SSHTerminal',
        component: () => import('../views/cmdb/SSHTerminal.vue'),
        props: true
      },
      // SQL管理路由
      {
        path: 'sql/query',
        name: 'QuerySQL',
        component: () => import('../views/sql-management/FixedQuerySQL.vue')
      },
      {
        path: 'sql/submit',
        name: 'SubmitSQL',
        component: () => import('../views/sql-management/SubmitSQL.vue')
      },
      {
        path: 'sql/audit',
        name: 'SQLAuditPage',
        component: () => import('../views/sql-management/SQLAudit.vue')
      },
      {
        path: 'sql/execute',
        name: 'SQLExecute',
        component: () => import('../views/sql-management/FixedQuerySQL.vue')
      },
      {
        path: 'sql/history',
        name: 'SQLHistoryPage',
        component: () => import('../views/sql-management/SQLHistory.vue')
      },
      {
        path: 'sql/database-instances',
        name: 'SQLDatabaseInstances',
        component: () => import('../views/cmdb/DatabaseInstances.vue')
      },
      {
        path: 'sql/my-tickets',
        name: 'MyTickets',
        component: () => import('../views/sql-management/MyTickets.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 验证token是否有效
const isTokenValid = (token) => {
  if (!token) return false

  try {
    // 解析JWT token
    const payload = JSON.parse(atob(token.split('.')[1]))
    const currentTime = Date.now() / 1000

    // 检查token是否过期
    return payload.exp > currentTime
  } catch (error) {
    console.error('Token解析失败:', error)
    return false
  }
}

// 清除无效的token
const clearInvalidTokens = () => {
  localStorage.removeItem('access_token')
  localStorage.removeItem('refresh_token')
  localStorage.removeItem('user_info')
}

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('access_token')

  // 检查token是否有效
  if (token && !isTokenValid(token)) {
    clearInvalidTokens()
  }

  const validToken = localStorage.getItem('access_token')

  if (to.meta.requiresAuth && !validToken) {
    next('/login')
  } else if (to.path === '/login' && validToken) {
    next('/')
  } else {
    next()
  }
})

export default router
